<template>
  <!-- 供应商/客户表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    top="5%"
    width="1373px"
    draggable
    :close-on-press-escape="false"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      :inline="true"
    >
      <el-card
        shadow="never"
        class="table-container mb-[10px] mt-[-10px] p-[70px] pb-[10px] pt-[10px]"
      >
        <el-row>
          <el-form-item label="供应商编号" prop="partnerCode">
            <el-input
              v-model="formData.partnerCode"
              placeholder="请输入供应商编号"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="供应商名称" prop="partnerName">
            <el-input
              v-model="formData.partnerName"
              placeholder="请输入供应商名称"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="所属公司" prop="organizationId">
            <el-select
              v-model="formData.organizationId"
              placeholder="请输选择所属公司"
              @change="corpChange"
              style="width: 250px"
              filterable
            >
              <el-option
                v-for="item in corpList"
                :key="item.id"
                :value="item.id"
                :label="item.organizationName"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="供应商组" prop="partnerGroupingId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.partnerGroupingId"
              @change="partnerGroupingChange"
              placeholder="请选择供应商组"
              clearable
              style="width: 250px"
            >
              <el-option
                v-for="item in partnerGroupingList"
                :key="item.id"
                :label="item.partnerGroupingName"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.partnerGroupingName }}</span>
          </el-form-item>
          <el-form-item label="国家" prop="country">
            <el-input
              v-model="formData.country"
              placeholder="请输入国家"
              style="width: 250px"
            />
          </el-form-item>
          <!-- 地区选择器 -->
          <el-form-item label="地区" prop="province">
            <el-input
              v-model="formData.province"
              placeholder="请输入地区"
              style="width: 250px"
            />
            <!--<el-cascader
              :options="areaOptions"
              v-model="formData.area"
              @change="areaHandleChange"
              style="width: 250px"
            />-->
          </el-form-item>
          <el-form-item label="邮政编码" prop="zipCode">
            <el-input
              v-model="formData.zipCode"
              placeholder="请输入邮政编码"
              style="width: 250px"
              clearable
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="详细地址" prop="addressDesc">
            <el-input
              v-model="formData.addressDesc"
              style="width: 1014px"
              type="textarea"
              :rows="2"
              maxlength="255"
              placeholder="请输入详细地址"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注">
            <el-input
              v-model="formData.remarks"
              style="width: 1014px"
              type="textarea"
              :rows="3"
              maxlength="255"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-row>
      </el-card>
      <el-tabs v-model="defaultTabValue" type="border-card">
        <el-tab-pane label="联系人" :name="1">
          <el-card shadow="never" class="table-container" style="height: 470px">
            <template #header>
              <el-button type="success" plain @click="handleContactAdd">
                <i-ep-plus />
                添加行</el-button
              >
            </template>
            <div class="formTable">
              <el-table
                :data="formData.contacts"
                style="width: 100%"
                :key="Math.random"
                max-height="375px"
                border
              >
                <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  width="90"
                />
                <el-table-column
                  label="姓名"
                  align="center"
                  props="contactName"
                  width="120"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'contacts.' + $index + '.contactName'"
                      :rules="rules.contactName"
                    >
                      <el-input
                        v-model="row.contactName"
                        placeholder="请输入联系人姓名"
                        style="width: 100px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="电话"
                  align="center"
                  props="contactPhone"
                  width="160"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'contacts.' + $index + '.contactPhone'"
                      :rules="rules.contactPhone"
                    >
                      <el-input
                        v-model="row.contactPhone"
                        placeholder="请输入联系人电话"
                        style="width: 140px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="邮箱"
                  align="center"
                  props="contactMail"
                  width="280"
                >
                  <template #default="{ $index, row }">
                    <el-form-item :prop="'contacts.' + $index + '.contactMail'">
                      <el-input
                        v-model="row.contactMail"
                        placeholder="请输入联系人邮箱"
                        style="width: 260px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="地址"
                  align="center"
                  props="contactAddress"
                  width="520"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'contacts.' + $index + '.contactAddress'"
                    >
                      <el-input
                        v-model="row.contactAddress"
                        placeholder="请输入联系人地址"
                        style="width: 500px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="90"
                  v-if="!props.isReadonly"
                >
                  <template #default="scope">
                    <el-button
                      :disabled="formData.contacts.length < 2"
                      type="danger"
                      link
                      @click.stop="handleContactDelete(scope.$index)"
                      ><i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="供应产品" :name="2">
          <el-card shadow="never" class="table-container" style="height: 470px">
            <template #header>
              <!--<el-button type="success" plain @click="handleProductAdd">
                <i-ep-plus />
                添加行</el-button
              >-->
              <el-button
                type="success"
                plain
                :disabled="formData.supplierId === ''"
                @click="openDialogAdd"
                v-if="!props.isReadonly"
              >
                <i-ep-plus />
                物料选择</el-button
              >
              <el-button
                type="danger"
                plain
                @click="handleDel"
                v-if="!props.isReadonly"
              >
                清空</el-button
              >
            </template>
            <div class="formTable">
              <el-table
                :data="formData.products"
                style="width: 100%"
                :key="Math.random"
                max-height="375px"
                border
              >
                <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  width="90"
                />
                <el-table-column
                  label="物料"
                  align="center"
                  props="materialId"
                  min-width="200"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'products.' + $index + '.materialId'"
                      :rules="rules.materialId"
                    >
                      <!--                      <el-select-->
                      <!--                        v-model="row.materialId"-->
                      <!--                        placeholder="请选择物料"-->
                      <!--                        @change="materialChange(row)"-->
                      <!--                        style="min-width: 240px"-->
                      <!--                        filterable-->
                      <!--                      >-->
                      <!--                        <el-option-->
                      <!--                          v-for="item in materials"-->
                      <!--                          :key="item.id"-->
                      <!--                          :label="item.materialCode + '-' + item.materialName"-->
                      <!--                          :value="item.id"-->
                      <!--                        />-->
                      <!--                      </el-select>-->
                      {{ row.materialCode }}-{{ row.materialName }}
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="规格"
                  align="center"
                  props="materialSpecification"
                  min-width="200"
                >
                  <template #default="{ $index, row }">
                    {{ row.materialSpecification }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="数量单位"
                  align="center"
                  props="quantityUnit"
                  max-width="120"
                >
                  <template #default="{ $index, row }">
                    <el-tag>
                      {{
                        dictionaryStore.filterDictName(
                          "MeasurementUnit",
                          typeTrim(row.unit)
                        )
                      }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  label="物料类型"
                  align="center"
                  props="materialType"
                  max-width="150"
                >
                  <template #default="{ $index, row }">
                    <el-tag>
                      {{
                        dictionaryStore.filterDictName(
                          "MaterialType",
                          typeTrim(row.materialType)
                        )
                      }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="100"
                  v-if="!props.isReadonly"
                >
                  <template #default="scope">
                    <el-button
                      :disabled="formData.products.length < 2"
                      type="danger"
                      link
                      @click.stop="handleProductDelete(scope.$index)"
                      ><i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <mdm-partner-product-add
      v-model:visible="addDialog123.visible"
      :title="addDialog123.title"
      :isMultiple="true"
      :data="addDialog123.data"
      :is-readonly="addDialog123.readvisible"
      @echo-info="getSelect"
      @change-visible="changeVisible"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { regionData, codeToText, pcaTextArr } from "element-china-area-data";
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMPARTNERADDORUPDATE",
  inheritAttrs: false,
});

let defaultTabValue = ref(1);
// 需要联动的数据
const areaOptions = ref(pcaTextArr);
// 需要回显的数据
const selectedOptions = ref([]);
const materials = ref([]);
// 变更事件
function areaHandleChange(value: any) {
  if (value) {
    // 赋值操作
    formData.province = value[0];
    formData.city = value[1];
    formData.region = value[2];
  }
}

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const checkMobile = (rule: any, value: any, callback: any) => {
  if (value != "") {
    let reg11 = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (reg11.test(value)) {
      callback();
    } else {
      callback(new Error("请输入正确格式电话号"));
    }
  } else {
    callback();
  }
};

const phoneRepeatCheck = (rule: any, value: any, callback: any) => {
  if (value) {
    const details = formData.contacts;
    var findCnt = 0;
    for (let i = 0; i < details.length; i++) {
      const element = details[i];
      if (element.contactPhone === value) {
        findCnt++;
      }
    }
    if (findCnt > 1) {
      return callback(new Error("此手机号已录入"));
    } else {
      callback();
    }
  }
};

const rules = reactive({
  partnerCode: [
    { required: true, message: "请输入供应商编码", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  partnerName: [
    { required: true, message: "请输入供应商名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  partnerGroupingId: [
    { required: true, message: "请输入供应商组", trigger: "change" },
  ],
  organizationId: [
    { required: true, message: "请选择所属公司", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  addressDesc: [
    { message: "请输入详细地址", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  country: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  area: [{ message: "请选择地区", trigger: "blur" }],
  province: [
    { message: "请输入地区", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  zipCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" },
    { validator: checkMobile, trigger: "blur" },
    { validator: phoneRepeatCheck, trigger: "blur" },
  ],
  materialId: [
    // { required: true, message: "请选择物料", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  partnerCode: "",
  partnerName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  addressDesc: "",
  country: "",
  province: "",
  city: "",
  region: "",
  street: "",
  houseCode: "",
  zipCode: "",
  contactName1: "",
  contactPhone1: "",
  contactName2: "",
  contactPhone2: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  deleted: "",
  area: [],
  contacts: [],
  products: [],
  partnerGroupingId: "",
  partnerGroupingName: "",
});

const contact = {
  id: "",
  partnerId: "",
  contactName: "",
  contactPhone: "",
  contactMail: "",
  contactAddress: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

const product = {
  id: "",
  partnerId: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  materialSpecification: "",
  quantityUnit: "",
  materialType: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

let corpList = ref([]);

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        partnerCode,
        partnerName,
        organizationId,
        organizationCode,
        organizationName,
        addressDesc,
        country,
        province,
        city,
        region,
        street,
        houseCode,
        zipCode,
        contactName1,
        contactPhone1,
        contactName2,
        contactPhone2,
        contacts,
        products,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
        partnerGroupingId,
        partnerGroupingName,
      } = newVal;
      Object.assign(formData, {
        id,
        partnerCode,
        partnerName,
        organizationId,
        organizationCode,
        organizationName,
        addressDesc,
        country,
        province,
        city,
        region,
        street,
        houseCode,
        zipCode,
        contactName1,
        contactPhone1,
        contactName2,
        contactPhone2,
        contacts,
        products,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
        partnerGroupingId,
        partnerGroupingName,
      });
      formData.area.push(province);
      formData.area.push(city);
      formData.area.push(region);
      addDialog123.data = products;
    } else {
      addDialog123.data = [];
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.addressDesc = "";
  formData.country = "";
  formData.province = "";
  formData.city = "";
  formData.region = "";
  formData.street = "";
  formData.houseCode = "";
  formData.zipCode = "";
  formData.contactName1 = "";
  formData.contactPhone1 = "";
  formData.contactName2 = "";
  formData.contactPhone2 = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.deleted = "";
  formData.partnerGroupingId = "";
  formData.partnerGroupingName = "";
  formData.area = [];
  formData.contacts = [];
  formData.products = [];
}

const loading = ref(false);

/** 联系人添加行 */
const handleContactAdd = () => {
  let sondata = JSON.parse(JSON.stringify(contact));
  formData.contacts.push(sondata);
};

/** 供应产品添加行 */
const handleProductAdd = () => {
  let sondata = JSON.parse(JSON.stringify(product));
  formData.products.push(sondata);
};

/** 联系人删除行 */
const isValidated = ref(false);
const handleContactDelete = (index: any) => {
  formData.contacts.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

/** 供应产品删除行 */
const handleProductDelete = (index: any) => {
  formData.products.splice(index, 1);
  // isValidated.value && formRef.value.validate(() => {});
};
/** 选择物料弹窗 */
/** 打开库存选择表单弹框 */
function openDialogAdd() {
  addDialog123.title = "物料选择";
  addDialog123.visible = true;
}
/** 清空 */
const handleDel = () => {
  formData.products.splice(0, formData.products.length);
};

const addDialog123 = reactive<DialogOption>({
  visible: false,
  title: "",
  data: [],
});
function changeVisible(value: boolean) {
  addDialog123.visible = value;
  if (!value) {
    addDialog123.data = {};
  }
}
// 接收选择器回调参数
function getSelect(options: any) {
  formData.products = [];
  for (const value of options) {
    // console.log(value); // 输出: 1, 2, 3
    value.quantityUnit = value.unit;
    value.createTime = "";
    value.createdUserId = "";
    value.createdUserName = "";
    value.lastUpdateTime = "";
    value.lastUpdatedUserId = "";
    value.lastUpdatedUserName = "";
    formData.products.push(value);
  }
  formData.products = uniqueByProperty(formData.products, "id");
  addDialog123.data = formData.products;
}
function uniqueByProperty<T, K extends keyof T>(arr: T[], key: K): T[] {
  return arr.filter((item, index, self) => {
    return self.findIndex((t) => t[key] === item[key]) === index;
  });
}

/** 供应商/客户保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmpartner/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getCorpList() {
  const data = await request({
    url: "/mdm/mdmpartner/getCorpList",
    method: "get",
  });
  corpList.value = data.data;
}

function corpChange() {
  const corp = corpList.value.find((item) => {
    return item.id === formData.organizationId;
  });
  formData.organizationCode = corp.organizationCode;
  formData.organizationName = corp.organizationName;
}

async function getMaterials() {
  const data = await request({
    url: "/mdm/mdmmaterial/getListByUser",
    method: "get",
  });
  materials.value = data.data;
}

function materialChange(row: any) {
  const material = materials.value.find((item) => {
    return item.id === row.materialId;
  });
  row.materialSpecification = material.materialSpecification;
  row.quantityUnit = material.unit;
  row.materialType = material.materialType;
}

function typeTrim(val: String) {
  if (!val) {
    return "未设置";
  } else {
    return val;
  }
}
//供应商组
const partnerGroupingList = ref([]);
async function getPartnerGrouping() {
  const data = await request({
    url: "/mdm/mdmpartnergrouping/getList",
    method: "post",
    data: {},
  });
  partnerGroupingList.value = data.data;
}
function partnerGroupingChange() {
  const grouping = partnerGroupingList.value.find((item) => {
    return item.id === formData.partnerGroupingId;
  });
  formData.partnerGroupingName = grouping.partnerGroupingName;
}
onMounted(() => {
  getCorpList();
  // getMaterials();
  getPartnerGrouping();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
